<?php

namespace AdminModule;

class SanitaPresenter extends AdminPresenter {

    public function renderDefault() {
        $this->template->sanitary = new \AdminModule\Models\Sanitary($this->db);
    }
    
    public function renderUpravit($id) {
        $this->getSanitaryById($id);
    }
    
    public function renderObrazky($id) {
        $sanitary = $this->getSanitaryById($id);
        $this->template->sanitary = $sanitary;
    }
    
    public function handleStahnout($id) {
        $sanitary = $this->getSanitaryById($id);
        if ($sanitary->update(array('published' => false))) {
            $this->flashMessage('Položka sanity byla stažena z webu');
        } else {
            $this->flashMessage('Položku sanity se nepodařilo z webu stáhnout', 'error');
        }        
        $this->invalidateControl('content');        
        if (!$this->isAjax()) {
            $this->redirect('this');
        }
    }
    
    public function handleZverejnit($id) {
        $sanitary = $this->getSanitaryById($id);
        if (count($sanitary->related('sanitary_has_images')) < 1) {
            $this->flashMessage('Položku sanity nelze uveřejnit bez obrázku. Přidejte alespoň jeden obrázek.', 'error');
        } else if ($sanitary->update(array('published' => true))) {
            $this->flashMessage('Položka sanity byla zveřejněna');
        } else {
            $this->flashMessage('Položku sanity se nepodařilo zveřejnit', 'error');
        }        
        $this->invalidateControl('content');
        
        if (!$this->isAjax()) {
            $this->redirect('this');
        }
    }
    
    public function handleSmazat($id) {
        $sanitary = $this->getSanitaryById($id);
        try {
            $this->deleteAllSanitaryImages($sanitary);
            $this->flashMessage('Položka sanity byla smazána');
        } catch (\Exception $exception) {
            $this->flashMessage('Položku sanity se nepodařilo smazat', 'error');
        }
        $sanitary->delete();
        $this->invalidateControl('content');        
        if (!$this->isAjax()) {
            $this->redirect('this');
        }
    }
    
    /**
     * Smazani vsech obrazku polozky sanity.
     * 
     * @param type \Nette\Database\Table\ActiveRow
     */
    private function deleteAllSanitaryImages(\Nette\Database\Table\ActiveRow $sanitary) {
        $imageModel = new \AdminModule\Models\Image($this->db);
        foreach ($sanitary->related('sanitary_has_images') as $sanitaryHasImage) {
            $image = $sanitaryHasImage->image;
            $imageModel->deleteWithFileByImageId($image->id_image);
        }
    }
    
    /**
     * 
     * @param int $id
     * @return \Nette\Database\Table\ActiveRow
     */
    private function getSanitaryById($id) {
        $sanitaryModel = new Models\Sanitary($this->db);
        $sanitary = $sanitaryModel->get($id);
        if (!$sanitary instanceof \Nette\Database\Table\ActiveRow) {
            $this->flashMessage('Položka sanity s id ' . $id . ' neexistuje', 'error');
            $this->redirect('default');
        }
        return $sanitary;
    }

    protected function createComponentSanitaryForm() {
        $form = new \Nette\Application\UI\Form;

        $manufacturer = new Models\Manufacturer($this->db);
        $manufacturersOptions = $manufacturer->getSelectOptions();

        $form->addText('title', 'Název')
                ->setRequired('Zadejte název');
        $form->addSelect('id_manufacturer', 'Výrobce', $manufacturersOptions);
        $form->addText('series', 'Série');
        $form->addText('code', 'Kód');
        $form->addTextArea('description', 'Popis');
        $form->addText('width', 'Šířka [cm]')
                ->addCondition(\Nette\Application\UI\Form::FILLED)
                ->addRule(\Nette\Application\UI\Form::FLOAT, 'Šířka musí být platné číslo');
        $form->addText('height', 'Výška [cm]')
                ->addCondition(\Nette\Application\UI\Form::FILLED)
                ->addRule(\Nette\Application\UI\Form::FLOAT, 'Výška musí být platné číslo');
        $form->addText('depth', 'Hloubka  [cm]')
                ->addCondition(\Nette\Application\UI\Form::FILLED)
                ->addRule(\Nette\Application\UI\Form::FLOAT, 'Hloubka musí být platné číslo');
        $form->addText('price', 'Cena')
                ->setRequired('Zadejte cenu')
                ->addRule(\Nette\Application\UI\Form::FLOAT, 'Cena musí být číslo');

        if ($this->action == 'upravit') {
            $sanitaryModel = new Models\Sanitary($this->db);
            $sanitary = $sanitaryModel->get($this->getParameter('id'));
            $form->setDefaults($sanitary);
            $form->addSubmit('upravit', 'Uložit');
        } else {
            $form->addSubmit('pridat', 'Přidat');
        }

        $form->onSuccess[] = $this->sanitaryFormSubmitted;
        return $form;
    }

    /**
     * Zpraconavi formaulare pro pridani/editaci sanity.
     * 
     * @param \Nette\Application\UI\Form $form
     */
    public function sanitaryFormSubmitted(\Nette\Application\UI\Form $form) {
        $values = $form->getValues(true);
        if ($this->action == 'pridat') {
            $this->addSanitary($values);
        } else if ($this->action == 'upravit') {
            $this->editSanitary($values);
            $this->redirect('this');
        }
        $this->redirect('default');
    }
    
    protected function createComponentImageForm() {
        $form = new \Nette\Application\UI\Form;
        $form->addText('title', 'Název');
        $form->addText('description', 'Popis');
        $form->addUpload('image', 'Soubor s obrázkem')
                ->setRequired('Vložte soubor s obrázkem');
        $form->addHidden('type')->setValue(\AdminModule\Helpers\Image::TYPE_SANITARY);
        $form->addSubmit('add', 'Přidat');
        $form->onSuccess[] = $this->imageFormSubmitted;
        return $form;
    }

    public function imageFormSubmitted(\Nette\Application\UI\Form $form) {
        $values = $form->getValues(true);
        $imageModel = new Models\Image($this->db);
        try {
            $image = $imageModel->insert($values);
            $sanitaryImageModel = new Models\SanitaryHasImages($this->db);
            $sanitaryImageModel->insert(array(
                'id_sanitary' => $this->getParameter('id'),
                'id_image' => $image->id_image,
            ));
            $this->flashMessage('Obrázek byl přidán');
        } catch (\LogicException $exception) {
            $this->flashMessage('Přidání obrázku se nezdařilo: ' . $exception->getMessage());
        }
        $this->redirect('this');
    }

    /**
     * Pridani polozky do sanity.
     * 
     * @param array $data
     */
    private function addSanitary($data) {
        $sanitaryModel = new \AdminModule\Models\Sanitary($this->db);
        try {
            $sanitaryModel->insert($data);
            $this->flashMessage('Zboží bylo přidáno do seznamu sanity');
        } catch (\Exception $exception) {
            $this->flashMessage('Zboží se do sanity nepodařilo přidat', 'error');
            \Nette\Diagnostics\Debugger::log($exception);
        }
    }

    /**
     * Editace polozky sanity.
     * 
     * @param array $data
     */
    private function editSanitary($data) {
        $sanitaryModel = new \AdminModule\Models\Sanitary($this->db);
        $sanitaryId = $this->getParameter('id');
        try {
            $sanitary = $sanitaryModel->get($sanitaryId);
            $sanitary->update($data);
            $this->flashMessage('Položka sanity byla upravena');
        } catch (\Exception $exception) {
            $this->flashMessage('Položku sanity se nepodařilo upravit', 'error');
            \Nette\Diagnostics\Debugger::log($exception);
        }
    }

    /**
     * Smazani obrazku.
     * 
     * @param int $idSanitary
     * @param int $idImage
     */
    public function handleSmazatObrazek($idImage) {
        $this->db->beginTransaction();
        try {
            $imageModel = new Models\Image($this->db);
            $imageModel->deleteWithFileByImageId($idImage);
            $this->flashMessage('Obrázek byl smazán');
            $this->db->commit();
        } catch (\Exception $exception) {
            $this->flashMessage('Smazání obrázku se nepodařilo', 'error');
            \Nette\Diagnostics\Debugger::log($exception);
            $this->db->rollBack();
        }
        $this->invalidateControl('content');

        if (!$this->isAjax()) {
            $this->redirect('this');
        }
    }

}
